package com.hupu.jrs.util

import android.content.Context
import android.text.TextUtils
import java.io.File
import java.util.regex.Pattern

/**
 * Created by sll on 2016/6/2.
 */
object HtmlUtil {
    private var htmlString: String? = null

    fun getHtmlString(mContext: Context): String? {
        if (!TextUtils.isEmpty(htmlString)) {
            return htmlString
        }
        val assetHtml = FileUtil.stringFromAssetsFile(mContext, "hupu_thread.html")
        val cachePath = ConfigUtil.getCachePath()
        if (!TextUtils.isEmpty(assetHtml)) {
            htmlString = assetHtml!!.replace("{hupu.js}",
                    String.format("file://%s", cachePath + File.separator + "hupu_thread.js"))
                    .replace("{jockey.js}",
                            String.format("file://%s", cachePath + File.separator + "jockey.js"))
                    .replace("{zepto.js}",
                            String.format("file://%s", cachePath + File.separator + "zepto.js"))
        }
        return htmlString
    }

    fun transImgToLocal(content: String): String {
        var content = content
        val pattern = Pattern.compile("<img(.+?)data_url=\"(.+?)\"(.+?)src=\"(.+?)\"(.+?)>")
        val localMatcher = pattern.matcher(content)
        while (localMatcher.find()) {
            val imageUrl = localMatcher.group(4)
            val localUrl = transToLocal(imageUrl)
            val localPath = "file://" + ConfigUtil.getCachePath() + File.separator + localUrl
            if (FileUtil.exist(localPath)) {
                content = content.replace(imageUrl, localUrl)
            }
        }
        localMatcher.reset()
        return content
    }

    @JvmOverloads
    fun transToLocal(url: String, dir: String? = null): String {
        var url = url
        url = url.substring(url.lastIndexOf("/") + 1)
        if (!TextUtils.isEmpty(dir)) url = dir!! + url
        return url
    }
}
